/*
 *  GeneticMinimizer.cpp
 *  Genetski
 *
 *  Created by Srđan Rašić on 11/17/11.
 *
 */

#include "GeneticMinimizer.h"
#include <vector>
#include <cmath>
#include <iostream>

GeneticMinimizer::GeneticMinimizer(Function& fun, SelectionOperator& selOper,
								   CrossoverOperator& crossOper, MutationOperator& mutatOper)
: _fun(fun), _selOper(selOper), _crossOper(crossOper), _mutatOper(mutatOper) {
	
}


void GeneticMinimizer::Initialize(int numberOfIndividuals, bool minimization, int precision) {
	_population = new Population(_fun, numberOfIndividuals, minimization, precision);
}

double GeneticMinimizer::Optimize(unsigned int numberOfIterations) {
	for (int i = 0; i < numberOfIterations; i++) {
		std::vector<int> sel = _selOper.Select(*_population, 3);

		std::pair<Chromosome, Chromosome> children = _crossOper.Crossover((*_population)[sel[1]], (*_population)[sel[2]]);
		
		(*_population)[sel[0]] = children.first;
		
		_mutatOper.Mutate((*_population)[sel[0]]);
	}
	
	int indMax = 0;
	for (int i = 1; i < _population->size(); i++)
		if ((*_population).Fitness(i) > (*_population).Fitness(indMax))
			indMax = i;
	
	//
	double dg = _fun.Domain().first;
	double gg = _fun.Domain().second;
	
	return dg + (*_population)[indMax].Value(0) / (pow(2.0, (*_population)[0].size()) - 1) * (gg-dg);
}